<template>
  <section>
    <el-container v-if="updateConfig.model==='dialog'">
      <el-main class="pad-no" >
        <el-button
          size="small"
          @click="uploadTrigger"
        >选择坐标</el-button>
      </el-main>
    </el-container>

    <el-container class="map--modelbox normal" v-if="updateConfig.model==='normal'">
          <el-main style="overflow: hidden;">
            <el-input
              placeholder="请输入内容"
              v-model="address"
              size="medium"
              class="serch"
              @change="serchChange"
            >
              <template
                slot="append"
                icon="el-icon-search"
              >
                <el-button @click="serchAdress">搜索地址</el-button>
              </template>
            </el-input>
            <baidu-map
              id="map"
              class="bm-view"
              :center="center"
              @ready="handler"
              ak="oi86AVnQ0bsKV8rtcQiBFyxlHmdPNY2o"
            ></baidu-map>
            <span class="font-help">提示：请拖动定位图标选择地址(如果定位地址与当前地址距离较远，请长按鼠标抓取定位图标不放后鼠标滚轮缩放地图定位)</span>
          </el-main>
        </el-container>

    <el-dialog
      title=""
      :append-to-body="true"
      :visible.sync="isShowModel"
      v-if="updateConfig.model==='dialog'"
    >
      <div
        v-show="isShowModel"
        class="map--modelbox"
        v-loading="mainLoing"
      >
        <el-container class="map-main">
          <el-main>
            <el-input
              placeholder="请输入内容"
              v-model="address"
              size="medium"
              class="serch"
              @change="serchChange"
            >
              <template
                slot="append"
                icon="el-icon-search"
              >
                <el-button @click="serchAdress">搜索地址</el-button>
              </template>
            </el-input>
            <baidu-map
              id="map"
              class="bm-view"
              :center="center"
              @ready="handler"
              ak="oi86AVnQ0bsKV8rtcQiBFyxlHmdPNY2o"
            ></baidu-map>
            <span class="font-help">提示：请拖动定位图标选择地址(如果定位地址与当前地址距离较远，请长按鼠标抓取定位图标不放后鼠标滚轮缩放地图定位)</span>
          </el-main>
          <el-footer class="footer flex-row flex-align-c flex-justify-b">
            <div class="flex-row flex-align-c flex-justify-b footer-button">
              <el-button
                style="margin-left: 10px;"
                size="small"
                type="primary"
                @click="getPosition"
              >确认</el-button>
              <el-button
                size="small"
                type="info"
                plain
                @click="uploadTrigger"
              >取消</el-button>
            </div>
          </el-footer>
        </el-container>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import { BaiduMap } from 'vue-baidu-map'
import { Message } from 'element-ui'
import defaultConfig from './utils/config'
export default {
  data() {
    return {
      center: {
        lng: 116.404288,
        lat: 39.918242
      },
      isShowModel: false,
      mainLoing: false,
      address: '',
      resuletPoint: {
        lng: 116.404288,
        lat: 39.918242
      }
    }
  },
  mixins: [defaultConfig.mixins],
  props: {
    defaultConfig: {
      type: Object,
      default: function() {
        return defaultConfig
      }
    }
  },
  components: {
    baiduMap: BaiduMap
  },
  computed: {

  },
  watch: {
    resuletPoint: {
      handler(newName, oldName) {
        // console.log(newName, newName.lat, 'address')
        newName.lat = parseFloat(newName.lat)
        newName.lng = parseFloat(newName.lng)
        this.resizePoint(newName)
      },
      immediate: false,
      deep: true
    },
    'config.initList': {
      handler(newData, oldData) {
        if (Array.isArray(newData) && newData.length > 0) {
          console.log(newData, newData.lng, '================>')
          this.resizePoint(newData)
        }
      },
      immediate: true,
      deep: true
    },
    isShowModel: {
      handler(newName, oldName) {
        if (this.$Map && this.$Marker && this.updateConfig.initList) {
          if (this.updateConfig.isEdit) {
            if (!newName) {
              this.resizePoint()
            }
          }
        }
      },
      immediate: false,
      deep: false
    }
  },
  mounted() {},
  methods: {
    handler({ BMap, map }) {
      this.mainLoing = true
      this.getUserLocal(this.updateConfig.isEdit, this.center)
    },
    serchChange(val) {
      this.address = val
    },
    serchAdress() {
      if (!!this.address && this.address !== '') {
        console.log(this.address)
        console.log(this.$LocalSearch.search(this.address))
        !!this.$LocalSearch && this.$LocalSearch.search(this.address)
      } else {
        Message({
          message: '请输入搜索地址',
          type: 'error'
        })
      }
    },
    serchResult(gh) {
      const point = gh.Br || gh.Ar || gh.Ir || gh.Hr
      // console.log(point, '========================>point')
      const lng = point[0].lng || point[0]['point']['lng']
      // console.log(lng, '========================>lng')
      const lat = point[0].lat || point[0]['point']['lat']
      // console.log(lat, '========================>lat')
      this.$Marker.setPosition(new BMap.Point(lng, lat))
      this.$Map.setCenter(new BMap.Point(lng, lat))
      this.resuletPoint = this.$Marker.getPosition()
      this.setSerchText(new BMap.Point(this.resuletPoint.lng, this.resuletPoint.lat), 'create')
      this.output()
    },
    mapInit(point, zoom) {
      var that = this
      const map = new BMap.Map('map')
      this.$Map = map
      this.$LocalSearch = new BMap.LocalSearch(map, {
        renderOptions: {
          autoViewport: true
        }
      })
      this.$Geocoder = new BMap.Geocoder()
      this.$LocalSearch.setSearchCompleteCallback(this.serchResult)
      map.centerAndZoom(point, zoom)
      var navigationControl = new BMap.NavigationControl({
        anchor: BMAP_ANCHOR_TOP_LEFT,
        type: BMAP_NAVIGATION_CONTROL_LARGE,
        enableGeolocation: true
      })
      map.addControl(navigationControl)
      map.enableScrollWheelZoom()
      map.enableInertialDragging()
      map.enableAutoResize()
      map.addControl(
        new BMap.MapTypeControl({
          mapTypes: [BMAP_NORMAL_MAP, BMAP_HYBRID_MAP]
        })
      )
      that.setMarke(point)
    },
    getUserLocal(isEdit, center) {
      const that = this
      if (isEdit) {
        const initPoint = this.updateConfig.initList
        if (!!initPoint && Array.isArray(initPoint) && initPoint.length > 0) {
          const [lng, lat] = initPoint
          that.mapInit(new BMap.Point(lng.value, lat.value), 15)
          that.setSerchText(new BMap.Point(lng.value, lat.value), 'create')
        } else {
          that.mapInit(new BMap.Point(center.lng, center.lat), 15)
          that.setSerchText(new BMap.Point(center.lng, center.lat), 'create')
        }
      } else {
        var geolocation = new BMap.Geolocation()
        geolocation.getCurrentPosition(function(r) {
          if (this.getStatus() === BMAP_STATUS_SUCCESS) {
            console.log('您的位置：' + r.point.lng + ',' + r.point.lat)
            center.lng = r.point.lng
            center.lat = r.point.lat
            that.mapInit(new BMap.Point(r.point.lng, r.point.lat), 18)
            that.setSerchText(new BMap.Point(r.point.lng, r.point.lat), 'create')
          } else {
            Message({
              message: '请开启浏览器定位功能！',
              type: 'error'
            })
            that.mainLoing = false
            that.uploadTrigger()
          }
        })
      }
    },
    setMarke(point) {
      const map = this.$Map
      const that = this
      const marker = new BMap.Marker(point, {
        enableMassClear: true,
        enableDragging: true,
        raiseOnDrag: true,
        title: '请您移动此坐标选择您的坐标',
        Animation: 'BMAP_ANIMATION_BOUNCE'
      })
      map.addOverlay(marker)
      marker.addEventListener('dragend', function() {
        const point = marker.getPosition()
        that.setSerchText(point)
        if (that.updateConfig.model === 'normal') {
          that.getPosition()
        }
      })
      this.$Marker = marker
      this.mainLoing = false
    },
    setSerchText(point, isCreate) {
      const that = this
      that.$Geocoder.getLocation(new BMap.Point(point.lng, point.lat), function(rs) {
        var addComp = rs.addressComponents
        if (isCreate !== 'create') {
          that.address = `${addComp.province} ${addComp.city} ${addComp.district} ${addComp.street} ${addComp.streetNumber}`
        }
      })
    },
    uploadTrigger() {
      this.isShowModel = !this.isShowModel
    },
    getPosition() {
      this.resuletPoint = this.$Marker.getPosition()
      console.log(this.resuletPoint, 'this.resuletPoint')
      this.output()
    },
    resizePoint(newPoint = { lng: 116.404288, lat: 39.918242 }) {
      if (this.$Map && this.$Marker) {
        if (Array.isArray(newPoint) && newPoint.length > 0) {
          const [lng, lat] = newPoint
          this.$Map.setCenter(new BMap.Point(lng.value, lat.value))
          this.$Marker.setPosition(new BMap.Point(lng.value, lat.value))
          this.setSerchText(new BMap.Point(lng.value, lat.value))
        } else {
          this.$Map.setCenter(new BMap.Point(newPoint.lng, newPoint.lat))
          this.$Marker.setPosition(new BMap.Point(newPoint.lng, newPoint.lat))
          this.setSerchText(new BMap.Point(newPoint.lng, newPoint.lat))
        }
      }
    },
    output() {
      const that = this
      this.$Geocoder.getLocation(new BMap.Point(that.resuletPoint.lng, that.resuletPoint.lat), function(rs) {
        const addComp = rs.addressComponents
        const address = `${addComp.province} ${addComp.city} ${addComp.district} ${addComp.street} ${addComp.streetNumber}`
        const copyResult = Object.assign({ address: address }, that.resuletPoint)
        // console.log(copyResult)
        if (
          Object.prototype.toString.call(that.changeEvt) === '[object Function]'
        ) {
          that.changeEvt(copyResult, that.updateConfig.bindKey)
        }
      })
    }
  },
  destroyed() {
    // this.
  }
}
</script>

<style lang="scss" scoped>
.map--modelbox {
  #map {
    min-height: 400px;
  }
  &.normal .el-main,.el-dialog__body {
    padding: 0;
  }
  .font-help {
    display: inline-block;
    margin-top: 20px;
  }
  &.normal,& .map-main {
    .serch {
      width: 100%!important;
      margin-bottom: 20px;
    }
    .el-input-group__append {
      cursor: pointer;
    }
  }
  .bm-view {
    width: 100%;
    height: 300px;
  }
  .anchorBL {
    display: none;
  }
}
</style>
